const http = require('http');
const fs = require('fs');
const url = require('url');

http.createServer((request, response) => {
	let {pathname} = url.parse(request.url);

	fs.stat(`www${pathname}`, (err, stat) => {
		if (err) {
			response.writeHead(404);
			response.write('Not Found');
			response.end();
		} else {
			// 判断客户端的请求有没有 If-Modified-Since，没有的话就是第一次请求文件
			if (request.headers['if-modified-since']) {
				// 获取服务器和客户端的文件的修改时间
				let oDate = new Date(request.headers['if-modified-since']);
				let time_client = Math.floor(oDate.getTime() / 1000);
				let time_server = Math.floor(stat.mtime.getTime() / 1000);

				// 如果服务器时间比客户端时间大，就需要更新
				if (time_server > time_client) {
					// 更新文件给客户端和第一次返回是一样的
					sendFileToClient();
				} else {
					response.writeHead(304);
					response.write('Not Midified');
					response.end();
				}
			} else {
				sendFileToClient();
			}

			function sendFileToClient() {
				let rs = fs.createReadStream(`www${pathname}`);

				let mtime = stat.mtime.toGMTString();
				response.setHeader('last-modified', mtime);

				rs.pipe(response);
			
				rs.on('error', err => {
					response.writeHead(404);
					response.write('Not Found');
					response.end();
				})
			}
		}
	})
}).listen(8080);